//
//  PKReadDetailViewController.m
//  PianKe
//
//  Created by lanou on 15/10/13.
//  Copyright (c) 2015年 李伟伟. All rights reserved.
//

#import "PKReadDetailViewController.h"
#import "PKRequestManager.h"
#import "PKReadDetailViewModel.h"
#import "PKReadDetailTableViewCell.h"
#import "PKReadWebViewController.h"
@interface PKReadDetailViewController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)NSMutableArray *detailModelArray;
@property(nonatomic,strong)UISegmentedControl *segmentedControl;
@property(nonatomic,strong)UIScrollView *mainScrollView;
@property(nonatomic,strong)UITableView *latestTableView;
@property(nonatomic,strong)UITableView *hottestTableView;
@property(nonatomic,copy)NSString *sort;;

@end

@implementation PKReadDetailViewController

-(NSMutableArray *)detailModelArray
{
    if (_detailModelArray == nil) {
        _detailModelArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _detailModelArray;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.frame = CGRectMake(0, 70, SCREEN_WITDTH, SCREEN_HEIGHT-70);
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(12, 18, 20, 20);
    backButton.backgroundColor = [UIColor grayColor];
    [backButton setImage:[UIImage imageNamed:@"后退"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToReadMainView) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:backButton];
    
    _segmentedControl = [[UISegmentedControl alloc]initWithItems:@[@"最新",@"最热"]];
    _segmentedControl.frame = CGRectMake(0, 70, SCREEN_WITDTH, 30);
    _segmentedControl.tintColor = [UIColor blackColor];
    _segmentedControl.selectedSegmentIndex = 0;
    [_segmentedControl addTarget:self action:@selector(changeContentOffset:) forControlEvents:UIControlEventValueChanged];
    
    
    [self.view addSubview:_segmentedControl];
    
    _mainScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 100, SCREEN_WITDTH, SCREEN_HEIGHT-100)];
    _mainScrollView.pagingEnabled = YES;
    _mainScrollView.delegate = self;
    _mainScrollView.contentSize = CGSizeMake(SCREEN_WITDTH * 2, 0);
    
    _latestTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WITDTH, SCREEN_HEIGHT-100) style:UITableViewStylePlain];
    _latestTableView.dataSource = self;
    _latestTableView.delegate = self;
    _latestTableView.rowHeight = 150;
    
    _hottestTableView = [[UITableView alloc]initWithFrame:CGRectMake(SCREEN_WITDTH, 0, SCREEN_WITDTH, SCREEN_HEIGHT-100) style:UITableViewStylePlain];
    _hottestTableView.dataSource = self;
    _hottestTableView.delegate = self;
    _hottestTableView.rowHeight = 150;
    
    [_mainScrollView addSubview:_latestTableView];
    [_mainScrollView addSubview:_hottestTableView];
    [self.view addSubview:_mainScrollView];
    
    
    [_latestTableView registerClass:[PKReadDetailTableViewCell class] forCellReuseIdentifier:@"latest"];
    
    _sort = @"addtime";
    [self requestData];
    
    
}
-(void)backToReadMainView
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)changeContentOffset:(UISegmentedControl *)seg
{
    NSInteger index = seg.selectedSegmentIndex;
    switch (index) {
        case 0:{
            _mainScrollView.contentOffset = CGPointMake(0, 0);

        }
            break;
        case 1:{
            _mainScrollView.contentOffset = CGPointMake(SCREEN_WITDTH, 0);
            _sort = @"hot";
            [self requestData];
            
        }
        default:
            break;
    }
    
}



-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat Y = _mainScrollView.contentOffset.x;
    if (Y == SCREEN_WITDTH){
        _segmentedControl.selectedSegmentIndex = 1;
        _sort = @"hot";
        [self requestData];
    }else
    {
        _sort = @"addtime";
        [self requestData];
        _segmentedControl.selectedSegmentIndex = 0;
    }
    
    
}


-(void)requestData
{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"deviceid"] = @"63A94D37-33F9-40FF-9EBB-481182338873";
    parDic[@"typeid"] = [NSString stringWithFormat:@"%ld",_typeid];
    parDic[@"client"] = @"1";
    parDic[@"sort"] = _sort;
    parDic[@"limit"] = @"10";
    parDic[@"version"] = @"3.0.2";
    parDic[@"auth"] = @"Wc06FCrkoq1DCMVzGMTikDJxQ8bm3Mrm2NpT9qWjwzcWP23tBKQx1c4P0";
    parDic[@"start"] = @"0";
    [PKRequestManager requestWithType:POST urlString:@"http://api2.pianke.me/read/columns_detail" parDic:parDic finish:^(NSData *data) {
        
        [self.detailModelArray removeAllObjects];

        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSArray *dicArray = dic[@"data"][@"list"];
        for (NSDictionary *modelDic in dicArray) {
            
            
            PKReadDetailViewModel *model = [[PKReadDetailViewModel alloc]init];
            [model setValuesForKeysWithDictionary:modelDic];
   
            [self.detailModelArray addObject:model];//懒加载是一个get方法，调用的时候才会创建数组，所以第一次要用self；
        }
        if ([_sort isEqualToString: @"hot"]) {
            [_hottestTableView reloadData];

        }else{
            [_latestTableView reloadData];
        }
       
     

        
    } error:^(NSError *error) {
        NSLog(@"========阅读详情页面数据请求失败============");
    }];
 
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _detailModelArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PKReadDetailTableViewCell *cell = [_latestTableView dequeueReusableCellWithIdentifier:@"latest" forIndexPath:indexPath];
    [cell configureCell:_detailModelArray[indexPath.row]];
   
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PKReadWebViewController *webVC = [[PKReadWebViewController alloc]init];
    webVC.contentid = [_detailModelArray[indexPath.row] contentid];
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
